﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics;

namespace Minestorm.Evolved.IoC
{
    public static class ReflectionHelper
    {
        public static T[] GetAttributes<T>(this MemberInfo member, Boolean inherit)
            where T : Attribute
        {
            return (T[])member.GetCustomAttributes(typeof(T), inherit);
        }

        public static T GetSingleAttribute<T>(this MemberInfo member, Boolean inherit)
            where T : Attribute
        {
            return member.GetAttributes<T>(inherit).FirstOrDefault();
        }

        public static T[] GetAttributes<T>(this Type type, Boolean inherit)
            where T : Attribute
        {
            return (T[])type.GetCustomAttributes(typeof(T), inherit);
        }

        public static T GetSingleAttribute<T>(this Type type, Boolean inherit)
            where T : Attribute
        {
            return type.GetAttributes<T>(inherit).FirstOrDefault();
        }

        public static MethodInfo GetGenericMethod(this Type type, String name, BindingFlags flags, params Type[] genericTypes)
        {
            return (from mi in type.GetMethods(flags)
                    where mi.IsGenericMethod && mi.Name == name && mi.GetGenericArguments().Length == genericTypes.Length
                    select mi).FirstOrDefault().MakeGenericMethod(genericTypes);
        }

        [DebuggerStepThrough]
        public static Object Invoke(this MethodInfo mi, Object instance, params Object[] args)
        {
            return mi.Invoke(instance, args);
        }
    }
}
